<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Model\Account;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class AuthMiddle implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var HttpResponse
     */
    protected $response;

    /**
     * @var RequestInterface
     */
    private $request;

    public function __construct(ContainerInterface $container,HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response  = $response;
        $this->request   = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 根据具体业务判断逻辑走向，这里假设用户携带的token有效
        $appid = $this->request->input('appid', '');
        if (empty($appid)){
            return $this->response->json(
                [
                    'code' => -1,
                    'msg'  => 'appid is null',
                    'data' => [],
                ]
            );
        }

        if (!Account::checkAppid($appid)){
            return $this->response->json(
                [
                    'code' => -1,
                    'msg'  => 'appid fail',
                    'data' => [],
                ]
            );
        }

        return $handler->handle($request);

    }
}